package com.xuecheng.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.ucenter.feignClient.CheckCodeServiceClient;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service("password")
public class PasswordAuthServiceImpl implements AuthService {

    @Autowired
    private XcUserMapper xcUserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private CheckCodeServiceClient checkCodeServiceClient;

    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {

        String checkcodekey = authParamsDto.getCheckcodekey();
        String checkcode = authParamsDto.getCheckcode();

        if (StringUtils.isEmpty(checkcode)){
            throw new RuntimeException("请输入验证码");
        }

        //进行验证码校验，远程调用验证码服务，去验证码服务哪里去校验
        Boolean verify = checkCodeServiceClient.verify(checkcodekey, checkcode);
        if (!verify || verify==null){
            //验证码错误
            throw new RuntimeException("验证码错误");
        }


        //验证账号是否存在
        String username = authParamsDto.getUsername();
        //查询数据库
        XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, username));
        //当查询不到username时抛出null即可，Spring Security会返回一个错误信息
        if (xcUser == null) {
            throw new RuntimeException("没有该账号信息");
        }
        //如果查询到拿到正确密码返回一个UserDetail对象由Spring Security进行比对
        String password = xcUser.getPassword();

        String formPassword = authParamsDto.getPassword();

        //验证密码
        //对比密码是否正确
        boolean matches = passwordEncoder.matches(formPassword, password);
        if (!matches) {
            throw new RuntimeException("账号密码不匹配");
        }
        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser, xcUserExt);

        return xcUserExt;
    }
}
